package handlers

import (
	"fun-trivial/cache"
	"fun-trivial/models"
	"github.com/gin-gonic/gin"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Article{
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	var list []models.Article
	err := models.DB.Order("id desc").Find(&list).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": list,
		"msg":  "查询成功",
	})
}
func ListID(c *gin.Context) {
	id := c.Query("id")
	var article models.Article
	err := models.DB.Where("id=?", id).First(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
	}
	redis_key := "list_id" + id
	countData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if countData == "" {
		cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": article,
		"msg":  "查询成功",
	})
}
